<?php

namespace App\Http\Controllers\Chanjet;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class TplusSaleGrossProfitAnalysis extends BaseController
{
    public function getExternalData(){
        $common = new TplusCommonController();
        $res = $common->getExternalData("TplusSaleGrossProfitAnalysis",$this->mangerinfo['org_id']);
        return $res;
    }
    public function getlist(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 0;

        $start_time = isTimestamp($request->start_time)?date('Y-m-d',$request->start_time):$request->start_time;
        $end_time = isTimestamp($request->end_time)?date('Y-m-d',$request->end_time):$request->end_time;

        $settle_customer = $request->settle_customer;

        if($start_time && $end_time){
            $dic[] = ['VoucherDate',$start_time,$end_time];
        }
        if($settle_customer){
            $dic[] = ['SettleCustomer',$settle_customer];
        }

        $dic[] = ['cpid',$memberinfo['cpid']];
        //取数来源
        $dic[] = ['FetchDataSource','00'];//00销货单 01销售出库单 02销售发票
        /***
         * 成本取值,影响到数据结果。
         *
         * 默认取 平均成本，2025.06.09
         *
        */
        $cost_value = '';
        if(isset($request->CostPriceType)){
            $dic[] = ['CostPriceType',$request->CostPriceType];//00记账成本 01参考成本 02最新成本 03 平均成本
            if($request->CostPriceType == '00') $cost_value = "记账成本";
            if($request->CostPriceType == '01') $cost_value = "参考成本";
            if($request->CostPriceType == '02') $cost_value = "最新成本";
            if($request->CostPriceType == '03') $cost_value = "平均成本";
        }
        $checkData = [
            'controllerName'=>'TplusSaleGrossProfitAnalysis',
            'org_id'=>$this->mangerinfo['org_id'],
            'condition'=>$dic
        ];
        $reportDataCheck = $this->checkReportCache($checkData);
        if($reportDataCheck['code'] != '000'){
            return response()->json(['code'=>'001','msg'=>'T+数据请求失败,请检查']);
        }
        if($reportDataCheck['data']){
            $request->cache_ids = $reportDataCheck['data'];
            \App\Models\Chanjet\TplusSaleGrossProfitAnalysis::whereIn('id',$request->cache_ids)->update(["cost_value"=>$cost_value]);
        }else{
            $request->cache_ids = [];
        }

        $list = \App\Models\Chanjet\TplusSaleGrossProfitAnalysis::getList($request, $memberinfo['cpid'], $isgetall);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }
}
